//
// Created by imagination on 4/1/25.
//
#include "application.h"
#include "settings.h"

#include "setting_page.h"
#include "cJSON/cJSON.h"

struct application app;

static bool load_screen_config()
{
    char content[128];
    lv_fs_file_t file;

    lv_fs_res_t ret = lv_fs_open(&file, "A:screen.json", LV_FS_MODE_RD);
    if (ret != LV_FS_RES_OK) {
        return false;
    }

    ret = lv_fs_read(&file, content, sizeof(content), NULL);
    if (ret != LV_FS_RES_OK) {
        goto label;
    }

    const cJSON *root = cJSON_Parse(content);
    if (root == NULL) {
        goto label;
    }

    const cJSON *item = cJSON_GetObjectItem(root, "dpi");
    if (item != NULL) {
        app.dpi = item->valueint;
    }
    item = cJSON_GetObjectItem(root, "hor_res");
    if (item != NULL) {
        app.hor_res = item->valueint;
    }
    item = cJSON_GetObjectItem(root, "ver_res");
    if (item != NULL) {
        app.ver_res = item->valueint;
    }
    item = cJSON_GetObjectItem(root, "orientation");
    if (item != NULL) {
        app.orientation = (char)item->valueint;
    }

    return true;

    label:
        lv_fs_close(&file);

    return false;
}

void app_init()
{
    load_screen_config();

    app.hor_res = 600;

    app.support_language[0].name = "English";
    app.support_language[0].locale_name = "en-us";
    app.support_language[1].name = "简体中文";
    app.support_language[1].locale_name = "zh-cn";
    app.support_language[2].name = "繁体中文";
    app.support_language[2].locale_name = "zh-tw";

    app.support_fonts[0].name = "14";
    app.support_fonts[0].font = &lv_font_simsun_14_cjk;
    app.support_fonts[1].name = "16";
    app.support_fonts[1].font = &lv_font_simsun_16_cjk;

    settings_load(&app.settings);

    setting_page_init();
}